<template>
  <BaseEdge 
    :id="id" 
    :style="edgeStyle" 
    :path="path" 
    :marker-end="markerEnd"
  />
  <EdgeLabelRenderer>
    <div
      v-if="label"
      :style="labelPosition"
      class="edge-label"
      :class="{ 'selected': selected }"
    >
      <div
        v-if="labelShowBg"
        class="label-bg"
        :style="labelBgStyleComputed"
      ></div>
      <span class="label-text" :style="labelStyle">{{ label }}</span>
    </div>
  </EdgeLabelRenderer>
</template>

<script setup>
import { BaseEdge, EdgeLabelRenderer, getBezierPath } from '@vue-flow/core'
import { computed } from 'vue'

const props = defineProps({
  id: String,
  sourceX: Number,
  sourceY: Number,
  targetX: Number,
  targetY: Number,
  sourcePosition: String,
  targetPosition: String,
  data: Object,
  style: Object,
  selected: Boolean,
  label: String,
  labelStyle: Object,
  labelShowBg: {
    type: Boolean,
    default: true
  },
  labelBgStyle: Object,
  labelBgPadding: {
    type: [Number, Array],
    default: [8, 4]
  },
  labelBgBorderRadius: {
    type: Number,
    default: 2
  }
})

// 计算直线路径和标签位置
const pathAndLabel = computed(() => {
  const [edgePath, labelX, labelY] = getBezierPath({
    sourceX: props.sourceX,
    sourceY: props.sourceY,
    sourcePosition: props.sourcePosition,
    targetX: props.targetX,
    targetY: props.targetY,
    targetPosition: props.targetPosition,
  })
  return { edgePath, labelX, labelY }
})

// 路径
const path = computed(() => pathAndLabel.value.edgePath)

// 计算标签位置
const labelPosition = computed(() => ({
  position: 'absolute',
  left: `${pathAndLabel.value.labelX}px`,
  top: `${pathAndLabel.value.labelY}px`,
  transform: 'translate(-50%, -50%)',
  pointerEvents: 'all',
  zIndex: 1000,
}))

// 边的样式
const edgeStyle = computed(() => ({
  strokeWidth: 2,
  stroke: props.selected ? '#3b82f6' : '#000000',
  strokeLinecap: 'round',
  ...props.style
}))

// 标签背景样式
const labelBgStyleComputed = computed(() => {
  const padding = Array.isArray(props.labelBgPadding) 
    ? props.labelBgPadding 
    : [props.labelBgPadding, props.labelBgPadding]
  
  return {
    position: 'absolute',
    top: '50%',
    left: '50%',
    transform: 'translate(-50%, -50%)',
    backgroundColor: 'white',
    padding: `${padding[0]}px ${padding[1]}px`,
    ...props.labelBgStyle
  }
})

// 箭头标记
const markerEnd = computed(() => {
  return props.selected ? 'url(#selected-arrow)' : 'url(#arrow)'
})
</script>

<style scoped>
.edge-label {
  position: relative;
  font-size: 12px;
  color: #374151;
  cursor: default;
}

.edge-label.selected .label-text {
  color: #3b82f6;
  font-weight: 500;
}

.label-bg {
  z-index: -1;
}

.label-text {
  position: relative;
  z-index: 1;
  white-space: nowrap;
  font-size: 12px;
}
</style> 